package top.csmcool.musicapi.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.FileSystemResource;
import top.csmcool.musicapi.util.ConfigUtil;


import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {


        String[] activeProfiles = environment.getActiveProfiles();
        if(activeProfiles.length > 0) {
            for (String activeProfile : activeProfiles) {
                loadConfigFile(environment,activeProfile);
            }
        } else {
            String active = System.getProperty("active") == null ? "dev" : System.getProperty("active");
            loadConfigFile(environment, active);
        }
    }

    private static void loadConfigFile(ConfigurableEnvironment environment, String active) {
        //tomcat路径
        String path = ConfigUtil.getConfigPath();
        Properties properties = new Properties();
        try(InputStream in = new FileInputStream(path)) {
            properties.load(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        MutablePropertySources propertySources = environment.getPropertySources();
        propertySources.addFirst(new PropertiesPropertySource("Config", properties));
    }
}